package com.example.JSON_Parser;

import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

public class MyActivity extends Activity {
    private ListView listView;
    private ArrayList<String> items;
    private ArrayAdapter<String> listAdapter;

    // Voorlopig statisch bestand
    private static String url = "http://codemix.be/json.txt";

    // JSON Node names
    private static final String TAG_ALBUMS = "albums";
    private static final String TAG_ID = "id";
    private static final String TAG_TITLE = "title";
    private static final String TAG_ARTIST = "artist";

    private static BufferedReader reader = null;

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        listView = (ListView) findViewById(R.id.mainListView);
        items = new ArrayList<String>();

        ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) {
            new MakeListView().execute();
        } else {
            //Wilt hij om een of andere reden niet tonen...
            Toast.makeText(getApplicationContext(), "No internet", Toast.LENGTH_SHORT).show();
            System.exit(1);
        }


    }

    private class MakeListView extends AsyncTask {

        @Override
        protected Object doInBackground(Object... params) {
            try {
                JSONObject jobj = new JSONObject(getContents(url));
                JSONArray albums = jobj.getJSONArray(TAG_ALBUMS);

                for (int i = 0; i < albums.length(); i++) {
                    JSONObject current = albums.getJSONObject(i);
                    String title = current.getString(TAG_TITLE);
                    items.add(title);
                }
            } catch (JSONException e) {

            }
            return null;
        }

        @Override
        protected void onPostExecute(Object o) {
            listAdapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.simplerow, items);
            listView.setAdapter(listAdapter);
            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Toast.makeText(getApplicationContext(), listView.getItemAtPosition(position).toString(), Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    public static String getContents(String url) {
        String contents = "";

        try {
            URLConnection conn = new URL(url).openConnection();

            InputStream in = conn.getInputStream();
            contents = convertStreamToString(in);
        } catch (MalformedURLException e) {

        } catch (IOException e) {

        }

        return contents;
    }

    private static String convertStreamToString(InputStream is) throws UnsupportedEncodingException {

        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        StringBuilder sb = new StringBuilder();
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
}